package com.runda.system.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;


import com.bbjob.mapper.SysUserRoleMapper;
import com.bbjob.mapper.UserMapper;
import com.bbjob.model.SysUserRole;
import com.bbjob.model.User;
import com.bbjob.util.service.impl.BaseService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.runda.entity.JwtUser;
import com.runda.system.service.UserService;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
public class UserServiceImpl extends BaseService<User> implements UserService, UserDetailsService {

	@Autowired
	private UserMapper usermapper;
	@Autowired
	private SysUserRoleMapper userrolemapper;
	
	@Autowired
	private BCryptPasswordEncoder encoder;
	

	@Override
	public int saveUser(User user) {
		user.setCreateTime(new Date());
		user.setEnable(1);
		user.setPassword(encoder.encode("123456"));
		int ok = usermapper.insertSelective(user);
		return ok;
	}

	@Override
	public int editUser(User user) {
		int ok = usermapper.updateByPrimaryKeySelective(user);
		return ok;
	}

	@Override
	public int deleteUser(Integer id) {
		int ok = usermapper.deleteByPrimaryKey(id);
		return ok;
	}

	@Override
	public PageInfo<User> getlist(User user, int page, int size) {
		PageHelper.startPage(page, size);
		Example example = new Example(User.class);
		Example.Criteria criteria = example.createCriteria();
		if (StringUtil.isNotEmpty(user.getUsername())) {
			criteria.andLike("username", "%" + user.getUsername() + "%");
		}
		example.setOrderByClause(" create_time desc");
		Map<Integer, String> map = new HashMap<>();
		
		List<User> resultList = usermapper.selectByExample(example);
		for (User user2 : resultList) {
			user2.setOrganname(map.get(user2.getOrganId()));
		}
		return new PageInfo<User>(resultList);
	}

	@Override
	public int setUserToRole(Integer userid, String role) {
		String[] roleid = role.split(",");
		Example example = new Example(SysUserRole.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("userId", userid);
		userrolemapper.deleteByExample(example);
		for (int i = 0; i < roleid.length; i++) {
			SysUserRole sys = new SysUserRole();
			sys.setRoleId(Integer.parseInt(roleid[i]));
			sys.setUserId(userid);
			userrolemapper.insertSelective(sys);
		}
		return 1;
	}

	@Override
	public List<Integer> getauth(Integer userid) {
		Example example = new Example(SysUserRole.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("userId", userid);
		List<SysUserRole> userrole = userrolemapper.selectByExample(example);
		List<Integer> list = new ArrayList<Integer>();
		for (SysUserRole sysUserRole : userrole) {
			list.add(sysUserRole.getRoleId());
		}
		return list;
	}

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user = new User();
		user.setUsername(username);
		User result=this.mapper.selectOne(user);
		if(result==null) {
			throw new UsernameNotFoundException("账户或密码不正确");
		}
		List<SimpleGrantedAuthority> authorities=null;
		if(result.getType()==-1) {
			 authorities=new ArrayList<SimpleGrantedAuthority>();
			 authorities.add(new SimpleGrantedAuthority("-1"));
		}else {
			List<Integer> roleIds=this.getauth(result.getId());
			authorities=roleIds.stream().map(roleId->{
				return new SimpleGrantedAuthority(roleId+"");
			}).collect(Collectors.toList());
		}
		return new JwtUser(result, authorities);
	}

	@Override
	public int resetPassword(Integer userid) {
		User user = new User();
		user.setId(userid);
		user.setPassword(encoder.encode("123456"));
		return usermapper.updateByPrimaryKeySelective(user);
	}

	@Override
	public int changePassword(Integer userid, String oldpasssord, String newpassword) {
		User user = usermapper.selectByPrimaryKey(userid);
		if (user == null) {
			// 没有找到用户
			return -1;
		}
		if(encoder.encode(oldpasssord).equals(user.getPassword())) {
			user.setPassword(encoder.encode(newpassword));
			return usermapper.updateByPrimaryKeySelective(user);
		}else {
			//旧密码不对
			return -2;
		}
	}
	
	@Override
	public User getUserInfo(User user) {
		if (user.getUniquecode() != null && !"".equals(user.getUniquecode())) {
			
		
			Example uExample = new Example(User.class);
			Criteria cU = uExample.createCriteria();
			cU.andEqualTo("enable", 1).andEqualTo("organId", user.getOrganId()).andEqualTo("username", user.getUsername());
			Criteria cA = uExample.createCriteria();
			cA.andEqualTo("type", -1).andEqualTo("username", user.getUsername());
			uExample.or(cA);
			
			List<User> list = usermapper.selectByExample(uExample);
			
			if (list.size() > 0) {
				
				return list.get(0);
			} else {
				
				return null;
			}
		} else {
			
			return null;
		}
		
	}

}